<template>
    <div class="app-container">
        <div class="search-container">
            <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
                <el-form-item label="患者姓名" prop="name">
                    <el-input v-model="queryParams.name" class="width-120"
                              clearable
                              placeholder="请输入患者姓名"
                              @clear="handleQuery"
                              @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="住院号:">
                    <el-input ref="hospitalNoInputRef" v-model="queryParams.hospitalNo" class="width-120"
                              clearable placeholder="请输入住院号检索">
                    </el-input>
                </el-form-item>
                <el-form-item label="结算序号" prop="feesNo">
                    <el-input v-model="queryParams.feesNo" class="width-120"
                              clearable
                              placeholder="请输入结算序号"
                              @clear="handleQuery"
                              @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="结算操作类型" prop="settelStatus">
                    <el-select v-model="queryParams.settelStatus" class="width-120" clearable
                               placeholder="请选择结算操作类型">
                        <el-option
                            v-for="dict in dictDataMap['settel_status_dict']"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <!--                <el-form-item label="退费收据号" prop="refundedFeesNo">-->
                <!--                    <el-input-->
                <!--                        v-model="queryParams.refundedFeesNo"-->
                <!--                        placeholder="请输入退费收据号"-->
                <!--                        clearable-->
                <!--                        @keyup.enter="handleQuery"-->
                <!--                    />-->
                <!--                </el-form-item>-->
                <el-form-item label="医保交易流水号" prop="ybSerialNo">
                    <el-input v-model="queryParams.ybSerialNo" class="width-120"
                              clearable
                              placeholder="请输入医保交易流水号"
                              @clear="handleQuery"
                              @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="参保类型" prop="canBaoType">
                    <el-select v-model="queryParams.canBaoType" class="width-120" clearable
                               placeholder="请选择参保类型">
                        <el-option
                            v-for="dict in dictDataMap['insurance_type']"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="结算操作人姓名" prop="operationUserName">
                    <el-input v-model="queryParams.operationUserName" class="width-120"
                              clearable
                              placeholder="请输入"
                              @clear="handleQuery"
                              @keyup.enter="handleQuery"
                    />
                </el-form-item>
              <el-row>
                <el-form-item>
                  <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
                </el-form-item>
              </el-row>
            </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
        </el-row>
        <el-row :gutter="10">
            <el-col :span="18">
                <el-table v-adaptive="290" :border="true" :data="inpFeesMasterList" :header-cell-style="$headerCellStyle"
                          :stripe="true" highlight-current-row
                          @row-click="inpFeesMasterRowClick">
                    <el-table-column :align="'center'" label="医保交易流水号" prop="ybSerialNo" width="200px"/>
                    <el-table-column :align="'center'" label="结算序号" prop="feesNo" width="150px">
                        <template #default="scope">
                            <span class="ys-css">{{ scope.row.feesNo }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="住院号" prop="hospitalNo" width="100px"/>
                    <el-table-column :align="'center'" label="患者姓名" prop="name"/>
                    <el-table-column :align="'center'" :show-overflow-tooltip="true" label="参保类型" prop="canBaoType"
                                     width="110px">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['insurance_type']"
                                           :value="scope.row.canBaoType"/>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="总费用(元)" prop="costs">
                        <template #default="scope">
                            <span class="ys-css">{{ parseFloat(scope.row.costs).toFixed(2) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="支付方式" prop="moneyType" width="70">
                        <template #default="scope">
                            <el-popover :title="scope.row.name + ' | 收据号' + scope.row.feesNo" :width="270"
                                        placement="right"
                                        trigger="hover">
                                <template #reference>
                                    <el-button type="primary">详情</el-button>
                                </template>
                                <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
                                    <el-descriptions-item v-for="(item, index) in scope.row.paymentsMoneyVoList"
                                                          :key="index"
                                                          min-width="80px">
                                        <template #label>
                                            <div style="display: flex">
                                                <div style="flex: 1">
                                                        <span style="font-weight: bold">{{ item.moneyTypeName }}
                                                        </span>
                                                </div>
                                            </div>
                                        </template>
                                        <span class="ys-css">{{ parseFloat(item.paymentAmount).toFixed(2) }}</span>元
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="结算操作类型" prop="settelStatus" width="90px">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['settel_status_dict']"
                                           :value="scope.row.settelStatus"/>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="结算时间" prop="createTime" width="130">
                        <template #default="scope">
                            <span>{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="结算操作人" prop="operationUserName" width="100px"/>
                    <el-table-column :align="'center'" label="退费收据号" prop="refundedFeesNo" width="110px"/>
                    <el-table-column :align="'center'" label="结账序号" prop="acctNo"/>
                    <el-table-column :align="'center'" label="退费时间" prop="refundedTime" width="130">
                        <template #default="scope">
                            <span>{{ $parseTime(scope.row.refundedTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="退费人姓名" prop="refundedPersonName"/>
                    <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="120">
                        <template #default="scope">
                            <!--                            <el-button-->
                            <!--                                type="success"-->
                            <!--                                @click="handleUpdate(scope.row)"-->
                            <!--                                v-hasPerm="['business:inpFeesMaster:edit']"-->
                            <!--                            >-->
                            <!--                                <template #icon>-->
                            <!--                                    <i-ep-edit/>-->
                            <!--                                </template>-->
                            <!--                                修改-->
                            <!--                            </el-button>-->
                            <!--                            <el-button-->
                            <!--                                type="danger"-->
                            <!--                                @click="handleDelete(scope.row)"-->
                            <!--                                v-hasPerm="['business:inpFeesMaster:remove']"-->
                            <!--                            >-->
                            <!--                                <template #icon>-->
                            <!--                                    <i-ep-delete/>-->
                            <!--                                </template>-->
                            <!--                                删除-->
                            <!--                            </el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
                <pagination
                    v-show="total>0"
                    v-model:limit="queryParams.pageSize"
                    v-model:page="queryParams.pageNum"
                    :total="total"
                    @pagination="getList"
                />
            </el-col>
            <el-col :span="6">
                <el-table ref="clinicOrdersRef" v-adaptive="290" :border="true" :data="inpFeesDetailList"
                          :header-cell-style="$headerCellStyle" :stripe="true" :summary-method="getSummaries"
                          highlight-current-row show-summary>
                    <el-table-column :align="'center'" label="收据项目" prop="classOnInpName"/>
                    <el-table-column :align="'center'" label="应收(元)" prop="costs" width="140">
                        <template #default="scope">
                            <span class="ys-css">
                                {{ parseFloat(scope.row.costs).toFixed(2) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="实收(元)" prop="charges" width="140">
                        <template #default="scope">
                            <span class="ys-css">
                                {{ parseFloat(scope.row.charges).toFixed(2) }}
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
export default {
    name: "InpFeesMaster"
}
</script>

<script lang="ts" setup>
import {
    getInpFeesMaster,
    selectPageInpFeesMaster,
} from "@/api/inpFees/inpFeesMaster.ts";

import {listInpFeesDetail} from "@/api/inpFees/inpFeesDetail.ts"

import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStore, useUserStoreHook} from "@/store/modules/user.ts";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('charge_flag_dict', 'insurance_type', 'settel_status_dict'))
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const formRef = ref();
const queryParamsRef = ref()
const inpFeesMasterList = ref([]);
// 结算明细list
const inpFeesDetailList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const emits =defineEmits(["getList"])
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    patientId: "",
    visitId: "",
    feesNo: "",
    settelStatus: "",
    refundedFeesNo: "",
    orgId: userInfo.orgId,
    ybSerialNo: "",
    canBaoType: "",
})

/** 查询结算主记录列表 */
function getList() {
    selectPageInpFeesMaster(queryParams.value).then((response: any) => {
        inpFeesDetailList.value = []
        inpFeesMasterList.value = response.rows;
        total.value = response.total;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    // proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.inpFeesMasterId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}


/** 修改按钮操作 */
function handleUpdate(row) {
    open.value = true;
    const _inpFeesMasterId = row.inpFeesMasterId || ids.value
    getInpFeesMaster(_inpFeesMasterId).then((response: any) => {
        title.value = "修改结算主记录";
    });
}

function inpFeesMasterRowClick(row: any) {
    listInpFeesDetail({"inpFeesMasterId": row.inpFeesMasterId}).then((res: any) => {
        inpFeesDetailList.value = res.data
    })
}

/** 提交按钮 */
// function submitForm() {
//     (formRef.value as any).validate(valid => {
//         if (valid) {
//             if (form.value.inpFeesMasterId != null) {
//                 updateInpFeesMaster(form.value).then((response: any) => {
//                     ElMessage.success("修改成功");
//                     open.value = false;
//                     getList();
//                 }).finally(() => {
//                 });
//             } else {
//                 addInpFeesMaster(form.value).then((response: any) => {
//                     ElMessage.success("新增成功");
//                     open.value = false;
//                     getList();
//                 }).finally(() => {
//                 });
//             }
//         }
//     });
// }

/** 导出按钮操作 */
function handleExport() {
    proxy.download('business/inpFeesMaster/export', {
        ...queryParams.value
    }, `inpFeesMaster_${new Date().getTime()}.xlsx`)
}

/**
 * 结算列表合计
 * @param param
 */
const getSummaries = (param: any) => {
    const {columns, data} = param
    const sums: (string | VNode)[] = []
    columns.forEach((column, index) => {
        if (index === 0) {
            // sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
            sums[index] = h('div', {style: {'float': 'right', 'color': 'rgb(51, 91, 249)', 'font-size': '15px'}}, [
                '合计：',
            ])
            return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => Number.isNaN(value))) {
            sums[index] = `￥ ${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                    return (Number(prev) + Number(curr)).toFixed(2)
                } else {
                    return (Number(prev)).toFixed(2)
                }
            }, 0)} 元`
        } else {
            sums[index] = 'N/A'
        }
    })

    return sums
}
getList();

defineExpose({
    getList
})
</script>
